package com.fetch;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;

public class ReadXMLFile {
	private static final String ns = null;
	   
	   private static String tagName;

	   private static String[] fieldNames;
	  
	   	   
	   private static List<String> readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
	        parser.require(XmlPullParser.START_TAG, ns, tagName);
            List<String> fields = new ArrayList<String>();
         
	        while (parser.next() != XmlPullParser.END_TAG) {
	        	   boolean toSkip = true;
	            if (parser.getEventType() != XmlPullParser.START_TAG) {
	                continue;
	            }
	            String tag = parser.getName();     

	            for(String s: fieldNames){
	            	if(tag.equals(s)){
	            		fields.add(readField(parser, s));
	            		toSkip = false;
	            	}            	
	            }
	            if(toSkip){
	            	skip(parser);
	            }
	        }
	      return fields;
	    }
	   
	   private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
		    if (parser.getEventType() != XmlPullParser.START_TAG) {
		        throw new IllegalStateException();
		    }
		    int depth = 1;
		    while (depth != 0) {
		        switch (parser.next()) {
		        case XmlPullParser.END_TAG:
		            depth--;
		            break;
		        case XmlPullParser.START_TAG:
		            depth++;
		            break;
		        }
		    }
		 }

	   private static String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
	        String result = "";
	        if (parser.next() == XmlPullParser.TEXT) {
	            result = parser.getText();
	            parser.nextTag();
	        } else if (parser.getName().equals("enclosure")){
	        	result = parser.getAttributeValue(1);
	        }
	        return result;
	    }
	    
	    // Processes title tags in the feed.
	    private static String readField(XmlPullParser parser, String fieldName) throws IOException, XmlPullParserException {
	        parser.require(XmlPullParser.START_TAG, ns, fieldName);
	        String title = readText(parser);
	        parser.require(XmlPullParser.END_TAG, ns, fieldName);
	        return title;
	    }
	      
	  
	    
	    private static List<List<String>> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
	        List<List<String>> entries = new ArrayList<List<String>>();
	        while (parser.next() != XmlPullParser.END_DOCUMENT) {
	            if (parser.getEventType() != XmlPullParser.START_TAG) {
	                continue;
	            }
	            String name = parser.getName();
	            // Starts by looking for the entry tag
	            if (name.equals(tagName)) {
	            	entries.add(readEntry(parser));
	            } 
	        }  
	        
	        return entries;
	    }
	    
		public static List<List<String>> parse(InputStream in, String tagName, String[] fieldNames ) {
			List<List<String>> list = null;
			try {
	        	ReadXMLFile.tagName = tagName;
	        	ReadXMLFile.fieldNames = fieldNames;
	            XmlPullParser parser = Xml.newPullParser();
	            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
	            parser.setInput(in, null);
	            parser.nextTag();
	            list = readFeed(parser);
	        } catch (XmlPullParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
	            try {
					in.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
			return list;
	    }

		static List<List<String>> list;
	    
	    public static List<List<String>> parse(final URL url, String tagName, String[] fieldNames ){
	    	ReadXMLFile.tagName = tagName;
        	ReadXMLFile.fieldNames = fieldNames;
        	
		    Thread thread = new Thread(new Runnable(){
		    	@Override
		    	   public void run() {
		    		try {	
						
						HttpURLConnection conn = (HttpURLConnection) url.openConnection();
						conn.setReadTimeout(10000 /* milliseconds */);
						conn.setConnectTimeout(15000 /* milliseconds */);
						conn.setRequestMethod("GET");
						conn.setDoInput(true);
						conn.connect();

						list = ReadXMLFile.parse(conn.getInputStream(), ReadXMLFile.tagName, ReadXMLFile.fieldNames);
						} catch (MalformedURLException e) {
						// 	TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
						// TODO Auto-generated catch block
							e.printStackTrace();
						}
		    	}
		    });
		      thread.start(); 
	        return list;
	    }
	    

	    
}
